//导入依赖包

const express= require('express');
const common = require('../../../libs/common');

const superagent = require("superagent");
const cheerio = require("cheerio");


let router = express.Router();
global.detailData='';
module.exports = router;


router.post('/',(req,res)=>{
    superagent.get("https://www.cars.com/research/sedan/?pageNum=0&rpp=29")
    .end((error, response) => {
        if(response){
            
            //获取页面文档数据
            var content = response.text;
            //cheerio也就是nodejs下的jQuery  将整个文档包装成一个集合，定义一个变量$接收
            let $ = cheerio.load(content);
            //定义一个空数组，用来接收数据
            let result=[];
            //分析文档结构  先获取每个li 再遍历里面的内容(此时每个li里面就存放着我们想要获取的数据)
            $("#mlp-listings>.mlp-container>.mlp-listings-container>.listingCard").each((index,value)=>{
                if($(value).find('.card-details>a>h4').text()!=''){
                    result.push({
                        title:$(value).find('.card-details>a>h4').text(),
                        img_src:'https://www.cars.com/'+$(value).find('a.card-image-link>div>img').attr('data-image-src'),
                        price:common.returnFloat($(value).find('.card-details>.card-details-info>.card-details-item>p.msrp').text().replace(/[\$,]/g,''))
                    })
                }
            })
            detailData=result;
            res.send(result)
        }
    })
})
